package com.machinecontroller.service;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;

import com.machinecontroller.StrongService;
import com.machinecontroller.constant.McConfig;
import com.machinecontroller.ui.MainActivity;
import com.machinecontroller.utils.ServiceUitl;


/**
 * http://blog.csdn.net/liuzg1220
 *
 * @author henry
 */
public class GuardService extends Service {
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    openActivity();
                    break;

                default:
                    break;
            }

        }
    };

    private void openActivity() {
        boolean isRun = ServiceUitl.isProcessRunning(GuardService.this,
                "com.machinecontroller");
        if (isRun == false) {
            try {
                startS2.openActivity();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 使用aidl 启动Service2
     */
    private StrongService startS2 = new StrongService.Stub() {

        @Override
        public void openActivity() throws RemoteException {
            Intent dialogIntent = new Intent(getBaseContext(), MainActivity.class);
            dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            getApplicationContext().startActivity(dialogIntent);
        }


    };

    /**
     * 在内存紧张的时候，系统回收内存时，会回调OnTrimMemory， 重写onTrimMemory当系统清理内存时从新启动Service2
     */
    @Override
    public void onTrimMemory(int level) {
        /*
         * 启动actvity
		 */
        openActivity();

    }

    @Override
    public void onCreate() {

        openActivity();
        /*
         * 此线程用监听Service2的状态
		 */
        new Thread() {
            public void run() {
                while (true) {
                    boolean isRun = ServiceUitl.isProcessRunning(GuardService.this,
                            "com.machinecontroller.ui.MainActivity");
                    if (!isRun) {
                        Message msg = Message.obtain();
                        msg.what = 1;
                        handler.sendMessage(msg);
                    }
                    try {
                        Thread.sleep(McConfig.MC_CHECK_ACTVITY_START_TIME);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return (IBinder) startS2;
    }
}
